package com.tensquare.user.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IDEA
 * author:zhiXiang-Chen
 * Date:2019/3/6
 * Time:10:30
 */

public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println(("++++++++++++"));

        //在这里解析token 然后用session存起来  服务端取出来判断就行了
        String authorization = request.getHeader("Authorization");
        //不空 且是Bearer才是我们要的token
        if (authorization != null && authorization.startsWith("Bearer")){
            String token = authorization.substring(7);//从第7开始就是token了 从0开始的  Bearer 空格+token
           //解析
            Claims claims = jwtUtil.parseJWT(token);
            if (claims!=null){
                if ("admin".equals(claims.get("roles"))){        //如果是管理员 存到域里面去 那边取出来判断就行了
                    request.setAttribute("admin_claims", claims);
                }
                if ("user".equals(claims.get("roles"))){        //如果是用户
                    request.setAttribute("user_claims", claims);
                }
            }

        }

        return true;
    }
}
